package leetcode_core.leetcode_1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TwoSumTarget {
    List<List<Integer>> twoSumTarget(int[] nums,int target){
        Arrays.sort(nums);//先对数组进行排序
        List<List<Integer>> ans = new ArrayList<>();
        int left = 0,right = nums.length-1;
        while(left<right){
            int sum = nums[left] + nums[right];
            int leftVal = nums[left];
            int rightVal = nums[right];
            //根据sum和target的比较,移动左右指针
            if(sum<target){
                while(left<right && nums[left] == leftVal){
                    left++;
                }
            }
            if(sum>target){
                while (left<right && nums[right] == rightVal){
                    right--;
                }
            }
            if(sum == target){
                List<Integer> t = new ArrayList<>();
                t.add(left);t.add(right);
                ans.add(t);
                //跳过所有的重复元素
                while(left<right && nums[left] == leftVal){
                    left++;
                }
                while (left<right && nums[right] == rightVal){
                    right--;
                }
            }
        }
        return ans;
    }


}
